﻿using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WebBrowser
{
    public partial class MainWindow : Window
    {
        private List<BrowserTab> _browserTabs = new List<BrowserTab>();
        private BookmarkManager _bookmarkManager;
        private HistoryManager _historyManager;

        public MainWindow()
        {
            InitializeComponent();
            _bookmarkManager = new BookmarkManager();
            _historyManager = new HistoryManager();
            CreateNewTab("https://www.bing.com");
        }

        private void CreateNewTab(string url = "about:blank")
        {
            // Create a new browser tab
            var browserTab = new BrowserTab(url);
            _browserTabs.Add(browserTab);
            
            // Add the tab to the tab control
            BrowserTabs.Items.Add(browserTab.TabItem);
            
            // Select the new tab
            BrowserTabs.SelectedItem = browserTab.TabItem;
            
            // Add the WebView to the content area
            BrowserContentArea.Children.Clear();
            BrowserContentArea.Children.Add(browserTab.WebView);
            
            // Handle new window requests
            browserTab.NewWindowRequested += (s, e) => 
            {
                e.Handled = true;
                CreateNewTab(e.Uri);
            };
            
            // Handle favicon changes
            browserTab.FaviconChanged += (sender, faviconUri) => 
            {
                if (browserTab.TabItem.IsSelected)
                {
                    UpdateFavicon(faviconUri);
                }
            };
            
            // Handle navigation completed for history tracking
            browserTab.NavigationCompleted += (sender, navigationData) => 
            {
                _historyManager.AddHistoryItem(navigationData.title, navigationData.url, navigationData.faviconUrl);
            };
            
            // Handle tab closing
            var closeButton = ((DockPanel)browserTab.TabItem.Header).Children[1] as Button;
            if (closeButton != null)
            {
                closeButton.Click += (s, e) => 
                {
                    // Don't close the last tab
                    if (BrowserTabs.Items.Count <= 1)
                    {
                        CreateNewTab();
                        return;
                    }
                    
                    // Remove from TabControl and list
                    BrowserTabs.Items.Remove(browserTab.TabItem);
                    _browserTabs.Remove(browserTab);
                    
                    // Clean up WebView2 resources
                    browserTab.WebView.Dispose();
                };
            }
        }

        private void BrowserTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                if (browserTab != null)
                {
                    // Update URL textbox
                    UrlTextBox.Text = browserTab.WebView.Source?.ToString() ?? string.Empty;
                    
                    // Update navigation buttons state
                    UpdateNavigationButtonsState();
                    
                    // Update bookmark button state
                    UpdateBookmarkButtonState();
                    
                    // Update favicon if available
                    if (browserTab.WebView.CoreWebView2 != null && browserTab.WebView.CoreWebView2.FaviconUri != null)
                    {
                        UpdateFavicon(browserTab.WebView.CoreWebView2.FaviconUri);
                    }
                    else
                    {
                        FaviconBorder.Visibility = Visibility.Collapsed;
                    }
                    
                    // Display the selected WebView in the content area
                    BrowserContentArea.Children.Clear();
                    
                    // If the WebView has a parent, remove it first
                    if (browserTab.WebView.Parent is Panel parentPanel)
                    {
                        parentPanel.Children.Remove(browserTab.WebView);
                    }
                    
                    BrowserContentArea.Children.Add(browserTab.WebView);
                }
            }
        }

        private void UpdateNavigationButtonsState()
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                if (browserTab != null)
                {
                    BackButton.IsEnabled = browserTab.CanGoBack;
                    ForwardButton.IsEnabled = browserTab.CanGoForward;
                    return;
                }
            }
            
            BackButton.IsEnabled = false;
            ForwardButton.IsEnabled = false;
        }

        public void UpdateUrlTextBox(string url)
        {
            UrlTextBox.Text = url;
            UpdateBookmarkButtonState();
        }
        
        private void UpdateFavicon(string faviconUri)
        {
            try
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(faviconUri);
                bitmap.EndInit();
                
                FaviconImage.Source = bitmap;
                FaviconBorder.Visibility = Visibility.Visible;
            }
            catch
            {
                // If favicon loading fails, hide the favicon
                FaviconBorder.Visibility = Visibility.Collapsed;
            }
        }

        private void Navigate(string url)
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                browserTab?.Navigate(url);
            }
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                browserTab?.GoBack();
            }
        }

        private void ForwardButton_Click(object sender, RoutedEventArgs e)
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                browserTab?.GoForward();
            }
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                browserTab?.Refresh();
            }
        }

        private void UrlTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Navigate(UrlTextBox.Text);
            }
        }

        private void NewTabButton_Click(object sender, RoutedEventArgs e)
        {
            CreateNewTab();
        }
        
        private void BrowserTabs_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // Get the element that was clicked
            var clickedElement = e.OriginalSource as DependencyObject;
            
            // Check if we clicked on a TabItem or its children
            bool clickedOnTab = false;
            while (clickedElement != null)
            {
                if (clickedElement is TabItem)
                {
                    clickedOnTab = true;
                    break;
                }
                clickedElement = VisualTreeHelper.GetParent(clickedElement);
            }
            
            // If we didn't click on a tab, create a new tab
            if (!clickedOnTab)
            {
                CreateNewTab();
                e.Handled = true;
            }
        }
        
        private void BookmarkButton_Click(object sender, RoutedEventArgs e)
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                if (browserTab?.WebView?.CoreWebView2 != null)
                {
                    var currentUrl = browserTab.WebView.Source?.ToString();
                    if (!string.IsNullOrEmpty(currentUrl))
                    {
                        if (_bookmarkManager.IsBookmarked(currentUrl))
                        {
                            // Remove bookmark
                            _bookmarkManager.RemoveBookmark(currentUrl);
                            MessageBox.Show("Bookmark removed!", "Bookmarks", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            // Add bookmark
                            var title = browserTab.WebView.CoreWebView2.DocumentTitle;
                            if (string.IsNullOrEmpty(title))
                                title = currentUrl;
                            
                            var faviconUrl = browserTab.WebView.CoreWebView2.FaviconUri;
                            _bookmarkManager.AddBookmark(title, currentUrl, faviconUrl);
                            MessageBox.Show("Bookmark added!", "Bookmarks", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        
                        UpdateBookmarkButtonState();
                    }
                }
            }
        }

        private void UpdateBookmarkButtonState()
        {
            if (BrowserTabs.SelectedItem is TabItem selectedTab)
            {
                var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                if (browserTab?.WebView?.Source != null)
                {
                    var currentUrl = browserTab.WebView.Source.ToString();
                    var isBookmarked = _bookmarkManager.IsBookmarked(currentUrl);
                    
                    if (BookmarkIcon != null)
                    {
                        BookmarkIcon.Fill = isBookmarked ? 
                            new SolidColorBrush(Color.FromRgb(255, 193, 7)) : // Gold color for bookmarked
                            new SolidColorBrush(Color.FromRgb(204, 204, 204)); // Gray for not bookmarked
                    }
                    
                    BookmarkButton.ToolTip = isBookmarked ? "Remove from bookmarks" : "Add to bookmarks";
                }
            }
        }

        private void MenuButton_Click(object sender, RoutedEventArgs e)
        {
            // Create context menu
            ContextMenu menu = new ContextMenu();
            
            // Add menu items
            MenuItem newTabItem = new MenuItem { Header = "Open New Tab" };
            newTabItem.Click += (s, args) => CreateNewTab();
            menu.Items.Add(newTabItem);
            
            MenuItem newWindowItem = new MenuItem { Header = "Open New Window" };
            newWindowItem.Click += (s, args) => 
            {
                // Create and show a new browser window
                MainWindow newWindow = new MainWindow();
                newWindow.Show();
            };
            menu.Items.Add(newWindowItem);
            
            menu.Items.Add(new Separator());
            
            MenuItem bookmarksItem = new MenuItem { Header = "Bookmarks" };
            bookmarksItem.Click += (s, args) => 
            {
                var bookmarksWindow = new BookmarksWindow(_bookmarkManager);
                bookmarksWindow.Owner = this;
                bookmarksWindow.BookmarkSelected += (sender, url) => 
                {
                    Navigate(url);
                };
                bookmarksWindow.ShowDialog();
            };
            menu.Items.Add(bookmarksItem);
            
            MenuItem historyItem = new MenuItem { Header = "History" };
            historyItem.Click += (s, args) => 
            {
                var historyWindow = new HistoryWindow(_historyManager);
                historyWindow.Owner = this;
                historyWindow.HistoryItemSelected += (sender, url) => 
                {
                    Navigate(url);
                };
                historyWindow.ShowDialog();
            };
            menu.Items.Add(historyItem);
            
            menu.Items.Add(new Separator());
            
            MenuItem downloadsItem = new MenuItem { Header = "View Downloads" };
            downloadsItem.Click += (s, args) => 
            {
                // Navigate to edge://downloads/ in the current tab
                if (BrowserTabs.SelectedItem is TabItem selectedTab)
                {
                    var browserTab = _browserTabs.Find(bt => bt.TabItem == selectedTab);
                    if (browserTab?.WebView?.CoreWebView2 != null)
                    {
                        // Try to navigate to the downloads page
                        try
                        {
                            browserTab.WebView.CoreWebView2.Navigate("edge://downloads/");
                        }
                        catch
                        {
                            // If edge://downloads/ is not supported, try chrome://downloads/
                            try
                            {
                                browserTab.WebView.CoreWebView2.Navigate("chrome://downloads/");
                            }
                            catch
                            {
                                MessageBox.Show("Downloads page is not available.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                        }
                    }
                }
            };
            menu.Items.Add(downloadsItem);
            
            // Show the context menu
            menu.PlacementTarget = sender as Button;
            menu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            menu.IsOpen = true;
        }
    }
}
